<template>
    <div>
      <DynamicTable :data-request="loadTableData" :columns="columns" showIndex>
        <template #toolbar>
          <a-button type="primary" @click="openAddDrawer({})"> <PlusOutlined />新增 </a-button>
        </template></DynamicTable
      >
    </div>
  </template>
  
  <script lang="tsx" setup>
    import { h, onMounted, reactive, ref, unref } from 'vue';
    import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
    import {
      baseColumns,
      type TableListItem,
      type TableColumnItem,
    } from '@/views/system/actionTemp/columns';
    import { useActionTempSchema } from '@/views/system/actionTemp/formSchemas';
    import {
        getActionTempList,
        deleteActionTemp,
        createActionTemp,
        editActionTemp
    } from '@/api/system/actionTemp/index';
    import {
        getOperActionList,getTempOperActionList
    } from '@/api/system/operAction/index';
    import { getMenuList } from '@/api/system/menu';
    import { useTable } from '@/components/core/dynamic-table';
    import { useFormDrawer } from '@/hooks/useDrawer/useFormDrawer';
    import { useDrawer } from '@/hooks/useDrawer/useDrawer';
    import OperActionTemp from './operActionTemp.vue';
    import { formatMenu2Tree, formatDept2Tree } from '@/core/permission/utils';
    import { cloneDeep } from 'lodash-es';
    import { message } from 'ant-design-vue';
  
    defineOptions({
      name: 'RoleList',
    });
  
    const editDrawerBindValue = reactive({
      tempData: {},
      startData: [],
      runData: [],
      hisData: [],
      startAll: [],
      startKeysAll: [],
      runAll: [],
      runKeysAll: [],
      hisAll: [],
      hisKeysAll: [],
    });
  
    const [DynamicTable, dynamicTableInstance] = useTable({
      size: 'small',
      rowKey: 'id',
      bordered: true,
    });
    // 加载表格数据
    const loadTableData = async (params) => {
      const data = await getActionTempList({
        ...params,
        ACTION_TEMP_NO:'',
        pagesize: params.limit,
      });
  
      return {
        list: data.result || [],
        pagination: {
          total: data.result,
          size: params.limit,
          page: params.page,
        },
      };
    };
  
    const [showDrawer] = useFormDrawer();
    const [DrawerRender] = useDrawer();
  
    const editFormRef = ref<any>(null);
  
    // 自定义组件抽屉
    const handleEditRole = async (record) => {
      console.log(record,'22222222');
      editDrawerBindValue.tempData = { ...record };
      handleRoleAuthAll(record.ACTION_TEMP_NO);
      DrawerRender.show({
        title: '编辑模版',
        width: 700,
        // 是否显示右上角确定取消
        defaultExtra: true,
        destroyOnClose: true,
        content: () => {
          return <OperActionTemp ref={editFormRef} defaultData={unref(editDrawerBindValue)}></OperActionTemp>;
        },
        // 确定方法执行
        onOk: async (values) => {
          const res = await editFormRef.value?.handleSubmit();
          if (!res) return;
          const operHisData=res.hisTimeData
          .map((item) => {
              return {
                NODE_ACTION_NICK_NAME: "",
                NODE_ACTION_SHOW_TYPE: 2,
                ACTION_NO: item,
             };
          });
          const operRunData=res.runTimeData
          .map((item) => {
              return {
                NODE_ACTION_NICK_NAME: "",
                NODE_ACTION_SHOW_TYPE: 1,
                ACTION_NO: item,
             };
          });
          const operStartData=res.startTimeDate
          .map((item) => {
              return {
                NODE_ACTION_NICK_NAME: "",
                NODE_ACTION_SHOW_TYPE: 0,
                ACTION_NO: item,
             };
          });
          const operData={
            hisTimeData: operHisData,
            runTimeData: operRunData,
            startTimeDate: operStartData,
          }
          console.log(operData,"operData22222222222");
          const result = await editActionTemp({...record,...operData});
          console.log(result);
          if (result.error == '200') {
            message.success('修改成功');
            dynamicTableInstance.reload();
          }
        },
      });
    };
    // Form 抽屉达开
    const openAddDrawer = async (record: Partial<TableListItem>) => {
      const [formRef] = await showDrawer({
        drawerProps: {
          title: `新增模版`,
          width: 700,
          defaultExtra: true,
          onFinish: async (values) => {
            await (record.ACTION_TEMP_NO ? editActionTemp : createActionTemp)(values);
            dynamicTableInstance.reload();
          },
        },
        formProps: {
          labelWidth: 100,
          schemas: useActionTempSchema(),
        },
      });
  
      formRef?.setFieldsValue({
        ...record,
      });
    };
    // 删除模版
    const delRowConfirm = async (record) => {
      if(record.ACTION_TEMP_TYPE===1)
      {
        message.error('系统内置模版，不可删除');
      }
      else{
        await deleteActionTemp(record);
      dynamicTableInstance.reload();
      }
    };
    
    // 获取模版对应的起草人、审核节点、历史节点中配置的审批动作
    const handleRoleAuthAll = async (id) => {
      const [selectOperAction] = await Promise.all([
        getTempOperActionList({ NODE_ACTION_TEMP_NO:id }),
      ]);
      //已选择的起草审批动作
      editDrawerBindValue.startData=selectOperAction?.result?.startTimeDate.map((item) => item.ACTION_NO);
      //已选择的审核审批动作
      editDrawerBindValue.runData=selectOperAction?.result?.runTimeData.map((item) => item.ACTION_NO);
      //已选择的历史审批动作
      editDrawerBindValue.hisData=selectOperAction?.result?.hisTimeData.map((item) => item.ACTION_NO);
    };
  
    // 获取所有数据
    const handleDefaultData = async () => {
      const [allOperAction] = await Promise.all([
        getOperActionList({ ACTION_NO: ""}),
      ]);
      const operActionList=allOperAction?.result??[];
      //起草节点可配置的数据
      editDrawerBindValue.startAll=operActionList.filter((item) => item.ACTION_START_ENABLE === 1).map((item) => {
        return Object.assign(item, {
          title: item.ACTION_NAME,
          key: item.ACTION_NO,
          value: item.ACTION_NO,
          formData: item,
          children: null,
        });
      });
      editDrawerBindValue.startKeysAll=operActionList.filter((item) => item.ACTION_START_ENABLE === 1).map((item) => item.ACTION_NO);
      //审核可配置的数据
      editDrawerBindValue.runAll=operActionList.filter((item) => item.ACTION_RUN_ENABLE === 1).map((item) => {
        return Object.assign(item, {
          title: item.ACTION_NAME,
          key: item.ACTION_NO,
          value: item.ACTION_NO,
          formData: item,
          children: null,
        });
      });
      editDrawerBindValue.runKeysAll=operActionList.filter((item) => item.ACTION_RUN_ENABLE === 1).map((item) => item.ACTION_NO);
      //历史可配置的数据
      editDrawerBindValue.hisAll=operActionList.filter((item) => item.ACTION_HIS_ENABLE === 1).map((item) => {
        return Object.assign(item, {
          title: item.ACTION_NAME,
          key: item.ACTION_NO,
          value: item.ACTION_NO,
          formData: item,
          children: null,
        });
      });
      editDrawerBindValue.hisKeysAll=operActionList.filter((item) => item.ACTION_HIS_ENABLE === 1).map((item) => item.ACTION_NO);
    };
  
    const columns: TableColumnItem[] = [
      ...baseColumns,
      {
        title: '操作',
        width: 220,
        dataIndex: 'ACTION',
        hideInSearch: true,
        align: 'center',
        actions: ({ record }) => [
          {
            label: '编辑',
            icon: h(EditOutlined),
            onClick: () => handleEditRole(record),
          },
          {
            label: '删除',
            danger: true,
            icon: h(DeleteOutlined),
            popConfirm: {
              title: '你确定要删除吗？',
              onConfirm: () => delRowConfirm(record),
            },
          },
        ],
      },
    ];
  
    onMounted(() => {
      handleDefaultData();
    });
  </script>
  